﻿
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_Mail_GetCompleteInfo_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_Mail_GetCompleteInfo_V2];
GO

CREATE PROCEDURE [dbo].[sproc_Mail_GetCompleteInfo_V2]
    @MailID     int
AS
BEGIN

DECLARE @mailBodyID int;

-- Mark the read flag
UPDATE dbo.UDS_Mail
SET
    ReadFlag = 1,
    @mailBodyID = MailBodyID
WHERE MailId = @MailID;
IF ( @@ROWCOUNT <> 1 )
BEGIN
    RAISERROR(N'Cannot find the specified mail "%d".', 16, 1, @MailID);
    RETURN -1;
END

-- Return the full info of the mail
SELECT
	M.MailID,
	B.Creator as Sender,
	(SELECT S.RealName FROM dbo.UDS_Staff S WHERE S.Staff_Name = B.Creator) as SenderRealName,
	B.TimeCreated as TimeSent,
	B.Subject,
	B.Body,
	B.TOList,
	B.CCList,
	B.BCCList,
	M.ReadFlag,
	B.ClassID,
	(SELECT ClassName FROM dbo.UDS_Class C WHERE C.Classid = B.ClassID) as ClassName,
	B.Importance,
	M.FolderType
FROM
    dbo.UDS_Mail M INNER JOIN dbo.UDS_MailBody B ON M.MailBodyID = B.MailBodyID
WHERE
    M.MailID = @MailID

-- Get all the attachments of this mail
SELECT * FROM dbo.UDS_MailAttachment WHERE MailBodyID = @mailBodyID;

END
GO
